#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
#include <unistd.h>
#include "tty.h"

struct termios tty, otty;

void tty_init(void)
{
  tcgetattr(STDIN_FILENO, &otty);
  tty = otty;
}

void tty_cbreak(void)
{
  tty.c_lflag     = tty.c_lflag & ~(ECHO | ECHOK | ICANON);
  tty.c_cc[VTIME] = 1;
  tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
		
void tty_cooked(void)
{
  tty.c_lflag     = otty.c_lflag;
  tty.c_cc[VTIME] = 0;
  tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}

void tty_exit(void)
{
  tcsetattr(STDIN_FILENO, TCSANOW, &otty);
}

char tty_testc(void)
{
  fd_set rdfs;
  struct timeval tv;

  FD_ZERO(&rdfs);
  FD_SET(STDIN_FILENO, &rdfs);
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  return select(STDIN_FILENO + 1, &rdfs, NULL, NULL, &tv);
}

char tty_getc(void)
{
  return getc(stdin);
}
